﻿using System;
using System.Collections.Generic;
using System.Linq;
using IQToolkit;
using IQToolkit.Data;
using Infrastucture.Factories;
using TimeSplicerModule.DataModels;
using TimeSplicerModule.DomainModels;

namespace TimeSplicerModule.Factories
{
    public interface ITeamCategoryFactory : Infrastucture.Factories.IFactory<TeamCategoryDataModel, TeamCategoryModel>
    {
        TeamCategoryModel CreateNew(CategoryModel category, TeamModel team);
        List<TeamCategoryModel> GetList(Func<TeamCategoryDataModel, bool> where, List<CategoryModel> categories, List<TeamModel> teams);
    }

    public class TeamCategoryFactory : Factory<TeamCategoryDataModel, TeamCategoryModel>, ITeamCategoryFactory
    {
        public TeamCategoryFactory(DbEntityProvider provider, IEntityTable<TeamCategoryDataModel> db)
            : base(provider, db)
        {

        }

        public TeamCategoryModel CreateNew(CategoryModel category, TeamModel team)
        {
            return new TeamCategoryModel
            {
                CategoryGuid = category.CategoryGuid,
                TeamGuid = team.TeamGuid,
                CategoryModel = category,
                Team = team
            };
        }

        public override TeamCategoryModel Add(TeamCategoryModel obj)
        {
            var existing = this.Get(x => x.CategoryGuid == obj.CategoryGuid
                && x.TeamGuid == obj.TeamGuid);

            if (existing == null)
                return base.Add(obj);
            else
                return existing;
        }


        public List<TeamCategoryModel> GetList(Func<TeamCategoryDataModel, bool> where, List<CategoryModel> categories, List<TeamModel> teams)
        {
            var recs = this.GetList(where);

            foreach (var r in recs)
            {
                r.CategoryModel = categories.FirstOrDefault(x => x.CategoryGuid == r.CategoryGuid);
                r.Team = teams.FirstOrDefault(x => x.TeamGuid == r.TeamGuid);
            }

            return recs;
        }
    }
}
